//
//  ContactSelect.swift
//  CooperSwift_Example
//
//  Created by 计海峰 on 2022/9/13.
//  Copyright © 2022 CocoaPods. All rights reserved.
//

import Foundation
import UIKit
import CooperSwift
import RxSwift
import SwiftyContacts

class ContactUserSelectModel: NSObject  {
    var phone: String = ""
    var name: String = ""
    var isSelect: Bool = false
    init(name: String, phone: String, isSelect: Bool) {
        self.name = name
        self.phone = phone
        self.isSelect = isSelect
    }
}

class ContactUserSelectCellModel: NSObject, TableCellConfigProtocol  {

    var model: Any?
    
    required init(_ model: Any?) {
        self.model = model
    }
    
    func cellCls() -> UITableViewCell.Type {
        return ContactUserSingleSelectCell.self
    }
    
    func cellOnce(_ cell: UITableViewCell) {

    }
    
    func cellEvery(_ cell: UITableViewCell) {
        
    }
    
}


class ContactUserSelectVM: NSObject, TableViewModelProtocol, BindKeyProtocol, UITableViewDelegate, FormResultProtocol {
    
    let bag = DisposeBag()
    
    func initDown() {
        requestAccess { result in
            if case .success(let isSuccess) = result  {
                self.loadContacts()
                debugPrint(isSuccess)
                
            }
            if case .failure(let error) = result  {
                debugPrint(error)
                
            }
        }
    }
    
    func loadContacts() {
        var users: [ContactUserSelectCellModel] = []
        fetchContacts { result in
            if case .success(let contacts) = result  {
                debugPrint(contacts)
                contacts.forEach { contact in
                    contact.phoneNumbers.forEach { phoneNumber in
                        debugPrint(phoneNumber.value.stringValue)
                        users.append(ContactUserSelectCellModel(ContactUserSelectModel(name: "\(contact.familyName)\(contact.givenName)", phone: phoneNumber.value.stringValue, isSelect: false)))
                    }
                }
            }
            if case .failure(let error) = result  {
                debugPrint(error)
            }
        }
        addFirstSectionItems(users)
    }
    
    @objc func btnTap(_ info: TableShowBtnConfig) {
        self.currentTV()?.reloadData()
        showWindowToast("单个按钮点击事件")
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return vm_tableView(tableView, heightForRowAt: indexPath)
    }
    
}
    
class ContactUserSelectVC: UIViewController, TableEnableProtocol, BindKeyProtocol {
    
    let vm = ViewModelFactory.tableVM(ContactUserSelectVM.self)
    let bag = DisposeBag()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        configAll(vm, disposeBag: bag, edges: .zero)
    }
    
}

